var gi;

function gameInfo() {
	this.round = $("#iRound").val();
	this.table = $("#iTable").val();
	this.section = $("#iSection").val();
	this.allResults = new Array();
	this.lowBoard = -1;
	this.highBoard = -1;
	this.lastRound = -1;
}
function playerInfo() {
	this.north = $("#inputN").val();
	this.south = $("#inputS").val();
	this.east = $("#inputE").val();
	this.west = $("#inputW").val();
}
function resultInfo() {
	this.board = $("#hiddenBoard").val();
	this.contractNumber = $("#select-choice-number").val();
	this.contractSuit = $("#select-choice-suit").val();
	this.redouble = $("#doubleButton").val();
	this.by = $("#select-choice-by").val();
	this.tricks = $("#select-choice-tricks").val();
	this.score = 0;

	this.computeScore = function() {

		var score = 0;
		var bidValue = 0;

		if (this.contractNumber != "PASS") {
			bidValue = parseInt(this.contractNumber);
		}

		var numTricks = bidValue;
		var trick = parseInt(this.tricks);
		if (trick.toString() != "NaN") {
			numTricks += trick;
		} else {
			trick = 0;
		}

		var code = 1;
		var vulnerable = false;
		var NSvulnerable = [ 2, 4, 5, 7, 10, 12, 13, 15 ];
		var EWvulnerable = [ 0, 3, 4, 6, 7, 9, 10, 13 ];
		if (this.redouble == "x") {
			code = 2;
		} else if (this.redouble == "xx") {
			/*
			 * lage funksjon til sjekk av double
			 */
			code = 4;
		}
		switch (this.by) {
		case "N":
		case "S": {
			var nr = parseInt(this.board) % 16;
			if (NSvulnerable.indexOf(nr) >= 0) {
				vulnerable = true;
			}
			break;
		}

		case "E":
		case "W": {
			var nr = parseInt(this.board) % 16;
			if (EWvulnerable.indexOf(nr) >= 0) {
				vulnerable = true;
			}
			break;
		}
		}
		if (bidValue == 0) {
			score = 0;
		} else {
			var drawValue = 0;
			var extra = 0;
			var bonus = 0;

			if (trick < 0) {
				/*
				 * didn't fulfill the contract
				 */
				var underTricks = (-1) * trick;
				if (vulnerable) {
					if (code == 4) {
						score = 400 + (underTricks - 1) * 600;
					} else if (code == 2) {
						score = 200 + (underTricks - 1) * 300;
					} else {
						score = underTricks * 100;
					}
				} else {
					if (code == 4) {
						if (underTricks <= 3) {
							score = 100 + (underTricks - 1) * 200;
						} else {
							score = 500 + (underTricks - 3) * 300;
						}
						score *= 2;
					} else if (code == 2) {
						if (underTricks <= 3) {
							score = 100 + (underTricks - 1) * 200;
						} else {
							score = 500 + (underTricks - 3) * 300;
						}
					} else {
						score = underTricks * 50;
					}

				}
				score = -score;
			} else {
				/*
				 * made the contract
				 */
				if (this.contractSuit == "NT") {
					drawValue = (40 + (bidValue - 1) * 30) * code;
					extra = trick * 30;
				} else if (this.contractSuit == "D" || this.contractSuit == "C") {
					drawValue = bidValue * 20 * code;
					extra = trick * 20;
				} else if (this.contractSuit == "H" || this.contractSuit == "S") {
					drawValue = bidValue * 30 * code;
					extra = trick * 30;
				}
				switch (code) {
				case 2:
					if (vulnerable) {
						extra = 50 + trick * 200;
					} else {
						extra = 50 + trick * 100;
					}
					break;
				case 4:
					if (vulnerable) {
						extra = 100 + trick * 400;
					} else {
						extra = 100 + trick * 200;
					}
					break;
				}
				if (drawValue >= 100) {
					if (vulnerable) {
						bonus = 500;
						if (bidValue == 6) {
							bonus += 750;
						} else if (bidValue == 7) {
							/*
							 * var 2 if'er etter hverandre
							 */
							bonus += 1500;
						}
					} else {
						bonus = 300;
						if (bidValue == 6) {
							bonus += 500;
						} else if (bidValue == 7) {
							bonus += 1000;
						}
					}
				} else {
					bonus = 50;
				}
				score = drawValue + extra + bonus;
			}
		}
		this.score = score;
	};
}

function sendRoundData() {
	gi = new gameInfo();
	var allright=true;
	var numberPatt = new RegExp("[0-9]+");
	if(numberPatt.test($("#iRound").val())==false){	
		allright=false;
	}
	if(numberPatt.test($("#iTable").val())==false){	
		allright=false;
	}
	var letterPatt = new RegExp("[A-Z]+");
	if(letterPatt.test($("#iSection").val())==false){	
		allright=false;
	}
	if(allright){
		$
			.ajax({
				type : "POST",
				url : "/checkPlayers",
				data : JSON.stringify(gi),
				dataType : "json",
			
				success : function(result) {
					gi.lowBoard = result.lowBoard;
					gi.highBoard = result.highBoard;
					gi.lastRound = result.lastRound;
					if (!(result.N == null && result.E == null
							&& result.S == null && result.W == null)) {
						var listItems = $("#playerList");
						listItems.empty();
						listItems.append("<li>N: " + result.N + "</li>");
						listItems.append("<li>S: " + result.S + "</li>");
						listItems.append("<li>E: " + result.E + "</li>");
						listItems.append("<li>W: " + result.W + "</li>");

						$("#block-tablePI").html("Table " + gi.table);
						$("#block-roundPI").html("Round " + gi.round);
						$("#block-boardsPI").html(
								"Boards " + gi.lowBoard + "-" + gi.highBoard);
						
						$(".headerText").text(
								(result.name).substring(10) + " "
										+ (result.name).substring(8, 10) + "/"
										+ (result.name).substring(5, 7) + "/"
										+ (result.name).substring(2, 4));
						$.mobile.changePage("#players");
					} else {
						$("#block-table").html("Table " + gi.table);
						$("#block-round").html("Round " + gi.round);
						$("#block-boards").html(
								"Boards " + gi.lowBoard + "-" + gi.highBoard);
						$.mobile.changePage("#membernr");
						$(".headerText").text(
								(result.name).substring(10) + " "
										+ (result.name).substring(8, 10) + "/"
										+ (result.name).substring(5, 7) + "/"
										+ (result.name).substring(2, 4));

					}

				},
				error : function(xhr, ajaxOptions, thrownError){
		            if(xhr.status==409){
		            	alert("Results have already been posted.\n" +
		            			"Check if the info is correct.\n" +
		            			"if it is, contact the organizer");
		            }else if(xhr.status==500){
		            	alert("Server doesn't except your input");
		            }else{
		            	alert(xhr.status)
		            }
		        } 
			});
	}else{
		alert("Check your input.");
	}
}

function sendPlayerInfo() {
	var pi = new playerInfo();
	gi.pi = pi;
	$.ajax({
		type : "POST",
		url : "/postPlayers",
		data : JSON.stringify(gi),
		dataType : "json",
		success : function(result) {

			var listItems = $("#playerList");
			listItems.empty();
			listItems.append("<li>N: " + result.N + "</li>");
			listItems.append("<li>S: " + result.S + "</li>");
			listItems.append("<li>E: " + result.E + "</li>");
			listItems.append("<li>W: " + result.W + "</li>");
			
			$.mobile.changePage("#players");
		},
		error : function(xhr, ajaxOptions, thrownError){
            if(xhr.status==500){
            	alert("Something has gone wrong with the server.\n" +
            			"Please notify the organizer.");
            }else{
            	alert("Something went wrong\n" +
            			"Please check you connection");
            }
            $.mobile.changePage("#membernr");
        }   
	});

}

function addToResultArray() {
	var i = $("#hiddenBoard").val();

	var result = new resultInfo();
	result.computeScore();
	gi.allResults[i] = result;
	updateSummaryTable();
	$.mobile.changePage("#resultSummary");

}

function toResultReg(id) {
	$("#block-tableRR").html("Table " + gi.table);
	$("#block-roundRR").html("Round " + gi.round);
	$("#block-boardsRR").html("Boards " + gi.lowBoard + "-" + gi.highBoard);
	$("#legendBoard").html("Board " + id);
	$("#hiddenBoard").val(id);
	$.mobile.changePage("#resultReg");
}

function updateSummaryTable() {
	$("#block-tableRS").html("Table " + gi.table);
	$("#block-roundRS").html("Round " + gi.round);
	$("#block-boardsRS").html("Boards " + gi.lowBoard + "-" + gi.highBoard);

	var Sum = $("#summary-table");
	Sum.empty();
	
	if (gi.allResults.length>0){
		var rowHead = document.createElement("tr");
		var headCol1 = document.createElement("th");
		var headCol2 = document.createElement("th");
		var headCol3 = document.createElement("th");
		headCol3.appendChild(document.createTextNode("NS"));
		var headCol4 = document.createElement("th");
		headCol4.appendChild(document.createTextNode("EW"));
		rowHead.appendChild(headCol1);
		rowHead.appendChild(headCol2);
		rowHead.appendChild(headCol3);
		rowHead.appendChild(headCol4);
		Sum.append(rowHead);
	}
	
	
	for ( var i = gi.lowBoard; i <= gi.highBoard; i++) {
		var result = gi.allResults[i];
		var row = document.createElement("tr");
		var col1 = document.createElement("td");
		col1.innerHTML = "<span>" + i + ": </span>";
		row.appendChild(col1);

		if (typeof (result) == "undefined") {
			var enter = document.createElement("button");
			/*enter.setAttribute("data-role", "button");
			enter.setAttribute("data-theme", "b");*/
			enter.appendChild(document.createTextNode("Enter board " + i));
			enter.bid = i;
			enter.onclick = function() {
				toResultReg(this.bid);
				clearResultRegPage();
			};
			var col6 = document.createElement("td");
			col6.appendChild(enter);
			row.appendChild(col6);
			Sum.append(row);
		} else {

			var col2 = document.createElement("td");
			var span = document.createElement("span");
			span.innerHTML = "<span>" + result.contractNumber + "</span>";
			col2.appendChild(span);
			col2.appendChild(setSymbol(result.contractSuit));
			col2.innerHTML += "<span>" + result.redouble + " by " + result.by
					+ " " + result.tricks + " " + "</span>";
			row.appendChild(col2);

			if(result.by.indexOf("N") != -1 || result.by.indexOf("S") != -1){
				
				var col3 = document.createElement("td");
				col3.align="right";
				col3.innerHTML = "<span>" + result.score + "</span>";
				row.appendChild(col3);
				
				var col4 = document.createElement("td");
				row.appendChild(col4);
			}else{
				var col3 = document.createElement("td");
				row.appendChild(col3);
				
				var col4 = document.createElement("td");
				col4.align="right";
				col4.innerHTML = "<span>" + result.score + "</span>";
				row.appendChild(col4);
			}
			

			var change = document.createElement("button");
			/*
			change.setAttribute("data-role", "button");
			change.setAttribute("data-theme", "b");
			*/
			change.appendChild( document.createTextNode("Change"));
			change.bid = i;
			change.onclick = function() {
				changeCalled(this.bid);
			};
			var col7 = document.createElement("td");
			col7.appendChild(change);
			row.appendChild(col7);
			Sum.append(row);
		}
	}
	$('#btn-page a').buttonMarkup();
	$('#btn-page').controlgroup();
}
function changeCalled(id) {

	var sNumber = $("#select-choice-number");
	sNumber[0].selectedIndex = gi.allResults[id].contractNumber - 1;
	sNumber.selectmenu('refresh');

	var sSuit = $("#select-choice-suit");
	sSuit.val(gi.allResults[id].contractSuit);
	sSuit.selectmenu('refresh');

	var byDirection = $("#select-choice-by");
	byDirection.val(gi.allResults[id].by);
	byDirection.selectmenu('refresh');

	var sTricks = $("#select-choice-tricks");
	sTricks.val(gi.allResults[id].tricks);
	sTricks.selectmenu('refresh');

	var sDoubleButton = $("#doubleButton");
	sDoubleButton.val(gi.allResults[id].redouble);
	sDoubleButton.selectmenu('refresh');

	toResultReg(id);
}

function clearResultRegPage() {
	var sNumber = $("#select-choice-number");
	sNumber[0].selectedIndex = 0;
	sNumber.selectmenu('refresh');
	var sSuit = $("#select-choice-suit");
	sSuit[0].selectedIndex = 0;
	sSuit.selectmenu('refresh');
	var byDirection = $("#select-choice-by");
	byDirection[0].selectedIndex = 0;
	byDirection.selectmenu('refresh');

	var sTricks = $("#select-choice-tricks");
	sTricks.val("=");
	sTricks.selectmenu('refresh');

	var sDoubleButton = $("#doubleButton");
	sDoubleButton[0].selectedIndex = 0;
	sDoubleButton.selectmenu('refresh');
}

function sendResultArray() {
	var checkResults = true;
	for ( var i = gi.lowBoard; i <= gi.highBoard; i++) {
		if (gi.allResults[i] == null) {
			checkResults = false;
		}
	}
	if (checkResults == true) {
		$.mobile.changePage("#empty");
		$.ajax({
			type : "POST",
			url : "/postResult",
			data : JSON.stringify(gi),
			dataType : "json",
		
			success : function() {
				var newRound = gi.round;
				if(newRound>=gi.lastRound){
					alert("All rounds Completed");
					newRound=1;
				}
				
				$("#iRound").val(newRound);
				$("#iTable").val("");
				$.mobile.changePage("/");
			},
			error: function (xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                alert(thrownError);
                $.mobile.changePage("#resultSummary");
            }
		});
	} else {
		alert("You got more boards to play");
	}
}

function setSymbol(type) {
	var symbol = document.createElement("font");
	symbol.color = "black";
	if (type == "S") {
		symbol.innerHTML = "&spades;";
	} else if (type == "H") {
		symbol.innerHTML = "&hearts;";
		symbol.color = "red";
	} else if (type == "D") {
		symbol.innerHTML = "&diams;";
		symbol.color = "red";
	} else if (type == "C") {
		symbol.innerHTML = "&clubs;";
	} else {
		symbol.innerHTML = "NT";
	}
	return symbol;
}

$(document).ready(function () {
	$("#select-choice-number").bind("change", function() {
		var select = $("#select-choice-tricks");
		var value = parseInt($("#select-choice-number").val());
		if (parseInt(value).toString() == "NaN") {
			value = -6;
		}
		
		select.empty();
		var base = (-1)*(value+6);
		for ( var i = 0; i <= 13; i++) {
			var option = document.createElement("option");
			var newValue = base+i;
			if (newValue == 0) {
				newValue = "=";
				newValue.selected = "selected";
			} else if (newValue > 0) {
				newValue = "+" + newValue;
			}
			option.value = newValue;
			option.innerHTML = newValue;
			select.append(option);
		}
		select.val("=");
		select.selectmenu('refresh');
	});
	
	
	
	$('#select-choice-number').iPhonePicker({width: '50px',heigth: '50px', imgRoot: 'images/'});
	$('#select-choice-number').remove();
	$('#select-choice-suit').iPhonePicker({width: '50px',heigth: '50px', imgRoot: 'images/'});
	$('#select-choice-suit').remove();
	$('#doubleButton').iPhonePicker({width: '50px',heigth: '50px', imgRoot: 'images/' });
	$('#doubleButton').remove();
	$('#select-choice-by').iPhonePicker({width: '50px',heigth: '50px', imgRoot: 'images/'});
	$('#select-choice-by').remove();
	$('#select-choice-tricks').iPhonePicker({ width: '50px',heigth: '50px', imgRoot: 'images/' });
	$('#select-choice-tricks').remove();
});
